<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-card class="search-card" v-show="showSearch">
      <el-form :model="queryParams">
        <el-row :gutter="20">
          <el-col :span="3">
            <el-form-item label="交班人">
              <el-select v-model="queryParams.shiftUserId" placeholder="请选择交班人" clearable filterable
                style="width: 100%">
                <el-option v-for="item in userOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="异常事件">
              <el-input v-model="queryParams.warningContent" placeholder="请输入异常事件描述" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="处理进展">
              <el-input v-model="queryParams.warningSolveStep" placeholder="请输入异常处理进展" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="状态">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 100%">
                <el-option label="全部" value="" />
                <el-option label="待接班" :value="1" />
                <el-option label="已完成" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" class="search-buttons">
            <el-button type="primary" @click="handleQuery">
              <el-icon class="el-icon--left">
                <Search />
              </el-icon>
              查询
            </el-button>
            <el-button @click="resetQuery">
              <el-icon class="el-icon--left">
                <Refresh />
              </el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-card">
      <div class="action-buttons">
        <el-button type="primary" @click="handleCreate">
          <el-icon class="el-icon--left">
            <Plus />
          </el-icon>
          新建交班
        </el-button>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="id" label="记录ID" width="100" align="center" />
        <el-table-column prop="shiftUserId" label="交班人" align="center">
          <template #default="{ row }">
            <el-tag>{{ getUserName(row.shiftUserId) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="shiftTime" label="交班时间" align="center" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.shiftTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="runData" label="当班运行数据" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="content-text">{{ row.runData || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="warningContent" label="异常事件" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="content-text">{{ row.warningContent || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="warningSolveStep" label="处理进展" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="content-text">{{ row.warningSolveStep || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleView(row.id)">查看</el-button>
            <el-button type="warning" link size="small" @click="handleEdit(row)" v-if="row.status === 1">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :total="total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" @closed="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="交班人" prop="shiftUserId">
              <el-select v-model="form.shiftUserId" placeholder="请选择交班人" style="width: 100%">
                <el-option v-for="item in userOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交班时间" prop="shiftTime">
              <el-date-picker v-model="form.shiftTime" type="datetime" placeholder="选择交班时间" style="width: 100%"
                value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="当班运行数据">
          <el-input v-model="form.runData" type="textarea" :rows="4" placeholder="请输入当班运行数据" maxlength="500"
            show-word-limit />
        </el-form-item>

        <el-form-item label="异常事件描述">
          <el-input v-model="form.warningContent" type="textarea" :rows="3" placeholder="请输入异常事件描述" maxlength="200"
            show-word-limit />
        </el-form-item>

        <el-form-item label="异常处理进展">
          <el-input v-model="form.warningSolveStep" type="textarea" :rows="3" placeholder="请输入异常处理进展" maxlength="200"
            show-word-limit />
        </el-form-item>
        <el-form-item label="文件" prop="fileIdsList">
          <UploadFile v-model:fileIds="form.fileIdsList" :fileList="fileList" v-if="dialog.visible" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">待接班</el-radio>
            <el-radio :label="2">已完成</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialog.visible" title="交班记录详情" width="900px">
      <el-tabs v-model="activeTab">
        <el-descriptions v-if="currentDetail" :column="2" border>
          <el-descriptions-item label="交班人">{{ getUserName(currentDetail.shiftUserId) }}</el-descriptions-item>
          <el-descriptions-item label="交班时间">{{ formatDateTime(currentDetail.shiftTime) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentDetail.status)">
              {{ getStatusName(currentDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="当班运行数据" :span="2">
            <pre class="detail-pre">{{ currentDetail.runData || '无' }}</pre>
          </el-descriptions-item>
          <el-descriptions-item label="异常事件描述" :span="2">
            <pre class="detail-pre">{{ currentDetail.warningContent || '无' }}</pre>
          </el-descriptions-item>
          <el-descriptions-item label="异常处理进展" :span="2">
            <pre class="detail-pre">{{ currentDetail.warningSolveStep || '无' }}</pre>
          </el-descriptions-item>
          <el-descriptions-item label="附件列表" :span="2"
            v-if="currentDetail.filesList && currentDetail.filesList.length > 0">
            <div v-for="file in currentDetail.filesList" :key="file.fileId" class="file-item">
              <el-link type="primary" :href="file.filePath" target="_blank">{{ file.originalFileName }}</el-link>
              <span class="file-size">({{ (file.fileSize / 1024).toFixed(2) }} KB)</span>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </el-tabs>
      <template #footer>
        <el-button @click="viewDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import UploadFile from '@/components/UploadFile'

// API导入
import {
  getShiftHandoverList,
  createShiftHandover,
  updateShiftHandover,
  deleteShiftHandover,
  getUserList,
  getShiftHandoverDetail,
  getShiftSuccessionDetail
} from '@/api/prod_operate/prod_run/shift/handover'

const showSearch = ref(true)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  shiftUserId: '',
  warningContent: '',
  warningSolveStep: '',
  status: ''
})

// 表单数据
const form = reactive({
  id: '',
  shiftUserId: '',
  shiftTime: '',
  runData: '',
  warningContent: '',
  warningSolveStep: '',
  fileIdsList: '',
  status: 1
})

// 对话框控制
const dialog = reactive({
  visible: false,
  title: '新建交班记录',
  isEdit: false
})

const viewDialog = reactive({
  visible: false
})
const fileList = ref([]);
// 表格数据
const tableData = ref([])
const userOptions = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const formRef = ref()
const submitting = ref(false)

// 详情数据
const currentDetail = ref(null)
const successionDetail = ref(null)
const activeTab = ref('shift')

// 表单验证规则
const rules = reactive({
  shiftUserId: [
    { required: true, message: '请选择交班人', trigger: 'change' }
  ],
  shiftTime: [
    { required: true, message: '请选择交班时间', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 计算属性
const dialogTitle = computed(() => {
  return dialog.isEdit ? '编辑交班记录' : '新建交班记录'
})

// 初始化数据
onMounted(() => {
  initData()
})

// 初始化数据
const initData = async () => {
  try {
    await Promise.all([
      fetchUserList(),
      getList()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  }
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await getUserList()
    userOptions.value = res.data || []
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 获取交班列表
const getList = async () => {
  try {
    loading.value = true
    const res = await getShiftHandoverList(queryParams)
    tableData.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取交班列表失败:', error)
    ElMessage.error('获取交班列表失败')
  } finally {
    loading.value = false
  }
}

// 查询处理
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    shiftUserId: '',
    warningContent: '',
    warningSolveStep: '',
    status: ''
  })
  getList()
}

// 分页处理
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  queryParams.pageNum = 1
  getList()
}

const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新建交班
const handleCreate = () => {
  dialog.isEdit = false
  resetForm()
  form.shiftTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  dialog.visible = true
}

// 编辑交班
const handleEdit = (row) => {
  dialog.isEdit = true
  Object.assign(form, row)
  dialog.visible = true
}

// 查看详情
const handleView = async (id) => {
  try {
    const [shiftRes, successionRes] = await Promise.all([
      getShiftHandoverDetail(id),
      getShiftSuccessionDetail(id)
    ])

    currentDetail.value = shiftRes.data
    successionDetail.value = successionRes.data
    activeTab.value = 'shift'
    viewDialog.visible = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}


// 删除记录
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除交班记录 "${row.id}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteShiftHandover(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  const ids = selectedRows.value.map(item => item.id)
  ElMessageBox.confirm(`确认删除选中的 ${ids.length} 条记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await Promise.all(ids.map(id => deleteShiftHandover(id)))
      ElMessage.success('批量删除成功')
      selectedRows.value = []
      getList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => { })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.clearValidate()
  }
  Object.assign(form, {
    id: '',
    shiftUserId: '',
    shiftTime: '',
    runData: '',
    warningContent: '',
    warningSolveStep: '',
    fileIdsList: '',
    status: 1
  })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true

    if (dialog.isEdit) {
      await updateShiftHandover(form)
      ElMessage.success('更新成功')
    } else {
      await createShiftHandover(form)
      ElMessage.success('创建成功')
    }

    dialog.visible = false
    getList()
  } catch (error) {
    console.error('提交失败:', error)
    if (error.errors) {
      return
    }
    ElMessage.error('操作失败')
  } finally {
    submitting.value = false
  }
}

// 工具函数
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  try {
    return dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss')
  } catch {
    return dateTime
  }
}

const getStatusName = (status) => {
  const statusMap = {
    1: '待接班',
    2: '已完成'
  }
  return statusMap[status] || '未知状态'
}

const getStatusTagType = (status) => {
  const typeMap = {
    1: 'warning', // 待接班
    2: 'success'  // 已完成
  }
  return typeMap[status] || 'info'
}

const getUserName = (userId) => {
  const user = userOptions.value.find(item => item.id === userId)
  return user ? user.name : '未知用户'
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-buttons {
  text-align: left;
}

.table-card {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.content-text {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.detail-pre {
  white-space: pre-wrap;
  word-break: break-all;
  margin: 0;
  font-family: inherit;
  line-height: 1.5;
  background: #f5f7fa;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.file-item {
  margin: 5px 0;
}

.file-size {
  color: #909399;
  margin-left: 8px;
  font-size: 12px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>